home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 12210 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  58 lines

  1. Path: cscsun3.larc.nasa.gov!hook
  2. From: hook@cscsun3.larc.nasa.gov (Ed Hook)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: sprintf() question
  5. Date: 29 Mar 1996 19:57:43 GMT
  6. Organization: CSC/NASA Langley Research Center
  7. Distribution: world
  8. Message-ID: <4jhfbn$p3@reznor.larc.nasa.gov>
  9. References: <31593522.76B3@cbm.com>
  10. Reply-To: hook@cscsun3.larc.nasa.gov
  11. NNTP-Posting-Host: cscsun3.larc.nasa.gov
  12.  
  13. In article <31593522.76B3@cbm.com>, Dave Payne <paynedc@cbm.com> writes:
  14. |> Question on sprintf():
  15. |> 
  16. |> Is it safe, and more importantly, is it ANSI standard, to use sprintf()
  17. |> to print into the same variable?  Consider this example:
  18. |> 
  19. |> char foo[100] = "foobar";
  20. |> 
  21. |> sprintf(foo,"%s%s","the string is",foo);
  22. |> 
  23. |> --------------------------------------------
  24. |> 
  25. |> Would the resulting string be "the string is foobar", or will this
  26. |> code cause problems because I'm using the same variable (foo) to
  27. |> print to as well as read from?
  28.  
  29.  The Standard says that this invokes undefined behavior, so don't do it.
  30.  Also, you could probably have answered your own question quite simply:
  31.  
  32. poseidon2.hook 57 % cat oops.c
  33. #include <stdio.h>
  34.  
  35. int main(void)
  36. {
  37.         char foo[80+1+1];
  38.  
  39.         sprintf(foo,"initial foo");
  40.         sprintf(foo,"the string is %s\n",foo);
  41.         fputs(foo,stdout);
  42.  
  43.         return 0;
  44. }
  45.  
  46. poseidon2.hook 58 % xlc -o oops oops.c
  47. poseidon2.hook 59 % oops
  48. the string is the string is 
  49. poseidon2.hook 60 % 
  50.  
  51.   See what I mean ?
  52.  
  53. -- 
  54.  Ed Hook                              |       Coppula eam, se non posit
  55.  Computer Sciences Corporation        |         acceptera jocularum.
  56.  NASA Langley Research Center         | Me? Speak for my employer?...<*snort*>
  57.  Internet: hook@cscsun3.larc.nasa.gov |        ... Get a _clue_ !!! ...
  58.